package com.binarysoft.service.common.http;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.handler.AbstractHandler;

import common.framework.dsb.client.DefaultServiceFactory;
import common.framework.dsb.client.ServiceFactory;
import common.framework.dsb.service.ServiceDescriptor;

public class DefaultHandler extends AbstractHandler {

	@Override
	public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException {
		Enumeration<String> enums = request.getHeaderNames();

		ServiceFactory serviceFactory = new DefaultServiceFactory();

		StringBuffer responseBuffer = new StringBuffer();
		try {
			List<String> startedServices = serviceFactory.listStartedService();
			List<ServiceDescriptor> beans = serviceFactory.list();
			responseBuffer.append("<center>");
			responseBuffer.append("<h5>DSB Services</h5>");
			responseBuffer.append("<table border=\"6\">");
			responseBuffer.append("<tr>");
			responseBuffer.append("<td><span style=\"font-weight:bold;\">Service Name</span></td>");
			responseBuffer.append("<td><span style=\"font-weight:bold;\">Startup</span></td>");
			responseBuffer.append("<td><span style=\"font-weight:bold;\">Status</span></td>");
			responseBuffer.append("</tr>");

			for (ServiceDescriptor sd : beans) {
				Object[] row = { sd.serviceName, startedServices.contains(sd.serviceName) ? "on" : "off", sd.startup };
				responseBuffer.append("<tr>");
				responseBuffer.append("<td>" + sd.serviceName + "</td>");
				responseBuffer.append("<td>" + sd.startup + "</td>");
				responseBuffer.append("<td>" + (startedServices.contains(sd.serviceName) ? "on" : "off") + "</td>");
				responseBuffer.append("</tr>");
			}
			responseBuffer.append("</table>");
		} catch (Exception e) {
			responseBuffer.append("<center>");
			responseBuffer.append("<h4>DSB Internal Error:" + e.getMessage() + "</h4>");
		}

		Request base_request = (request instanceof Request) ? (Request) request : HttpConnection.getCurrentConnection().getRequest();
		base_request.setHandled(true);
		response.setStatus(HttpServletResponse.SC_OK);
		response.setContentType("text/html");
		response.getOutputStream().print(responseBuffer.toString());
	}

}
